﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Project;
using AMM.Business.Store;
using AMM.CustomClassLibrary;
using AMM.CustomWinComponents.Validator;
using AMM.Model;
using AMM.Model.Project;
using AMM.Model.Store;

namespace AMM.UserControls {
    public partial class QualityOrderEditControl : BaseEditControl {

        private FlexBindingSource<QualityOrder> _fbs;
        private SuspenseOrderProcessor _suspenseOrderProcessor;

        public override object BaseEditModel {
            get {
                this._fbs.CurrentItem.QualityOrderDetails =
                    this.dgvMaterialEdit.GetDataSourceEx<QualityOrderDetail>(this._fbs.CurrentItem.ClassStatus != ClassStatus.Added);
                return this._fbs.CurrentItem;
            }
            set {
                if (this._fbs == null) { this._fbs = new FlexBindingSource<QualityOrder>(); }
                this._fbs.CurrentItem = (QualityOrder)value;
            }
        }

        public QualityOrderEditControl() {
            this.InitializeComponent();
        }

        private void BindMaterial(int suspenseId) {
            MaterialProcessor materialProcessor = new MaterialProcessor(int.MaxValue);
            List<MaterialViewModel> materialList = materialProcessor.FetchMaterialViewModelListBySuspenseOrderId(suspenseId);
            //if (suspenseId == 0) {
            //    MaterialSearchModel searchModel = new MaterialSearchModel() { IsEnabled = true };
            //    materialList = materialProcessor.FetchMaterialViewModelList(searchModel);
            //}
            //else {
            //    materialList = materialProcessor.FetchMaterialViewModelListByProcumentOrderId(suspenseId);
            //}

            this.Material.DisplayMemberEx = "Code";
            this.Material.ValueMemberEx = "Key";
            this.Material.HeightEx = 300;
            this.Material.WidthEx = 400;
            this.Material.PageSizeEx = 20;
            this.Material.DataBind(new MaterialViewModel(), x => new { x.MaterialType, x.Code, x.Name, x.Remarks }, materialList);
        }

        private void BindSuspense(int suspenseOrderId = 0) {
            SuspenseOrderSearchModel searchModel = new SuspenseOrderSearchModel();
            SuspenseOrderProcessor suspenseProcessor = new SuspenseOrderProcessor(int.MaxValue);
            List<SuspenseOrderViewModel> suspenseList = suspenseProcessor.FetchSuspenseOrderViewModelList(searchModel);
            /*
            if (suspenseOrderId != 0 && !suspenseList.Any(x => x.Key == suspenseOrderId)) {
                SuspenseOrder suspenseOrder = suspenseProcessor.FetchSuspenseOrderById(suspenseOrderId);
                suspenseList.Add(new SuspenseOrderViewModel() {
                    Key = suspenseOrder.SuspenseOrderId,
                    Code = suspenseOrder.Code
                });
            }
            */

            this.ddlSuspense.DisplayMemberEx = "Code";
            this.ddlSuspense.ValueMemberEx = "Key";
            this.ddlSuspense.HeightEx = 300;
            this.ddlSuspense.WidthEx = 400;
            this.ddlSuspense.PageSizeEx = 20;
            this.ddlSuspense.DataBind(new SuspenseOrderViewModel(), x => new { x.Code, x.ProcurementOrderCode, x.Remarks }, suspenseList);
        }

        private void CreateFormBindings() {
            this._fbs.CreateBinding(this.ddlSuspense, x => x.SelectedValueEx, y => y.SuspenseOrderId);
            this._fbs.CreateBinding(this.tbCode, x => x.Text, y => y.Code);
            this._fbs.CreateBinding(this.tbRemarks, x => x.Text, y => y.Remarks);
        }

        private void BindValidation() {
            this.ValidatorForEdit.SetType(this.tbCode, ValidationType.Required | ValidationType.RegularExpression);
            this.ValidatorForEdit.SetRequiredMessage(this.tbCode, this.RequiredMessage);
            this.ValidatorForEdit.SetRegularExpression(this.tbCode, "^[A-Za-z0-9-]+$");
            this.ValidatorForEdit.SetRegularExpressionMessage(this.tbCode, "编码只能由字母，数字，连接线组成");

            this.ValidatorForEdit.SetType(this.ddlSuspense, ValidationType.Required);
            this.ValidatorForEdit.SetRequiredMessage(this.ddlSuspense, this.RequiredMessage);
        }

        private void QualityEditControl_Load(object sender, EventArgs e) {
            if (this._fbs == null) { this._fbs = new FlexBindingSource<QualityOrder>(); }
            this._suspenseOrderProcessor = new SuspenseOrderProcessor();

            this.BindMaterial(this._fbs.CurrentItem.SuspenseOrderId);
            this.BindSuspense(this._fbs.CurrentItem.SuspenseOrderId);
            this.dgvMaterialEdit.DataSourceEx = this._fbs.CurrentItem.QualityOrderDetails.ToList();
            this.CreateFormBindings();
            this.BindValidation();

            this.ddlSuspense.Enabled = false;
            if (this._fbs.CurrentItem.ClassStatus == ClassStatus.Added) {
                string autoCode = CommonHelper.GenerateAutoCode("Q");
                int maxNumber = new QualityOrderProcessor().GetTheMaxFlowNumber(autoCode);
                this._fbs.CurrentItem.Code = CommonHelper.GendrateSpecificCode(autoCode, maxNumber);
                this.ddlSuspense.Enabled = true;
            }
        }

        private void ddlSuspense_ValueChanged(object sender, EventArgs e) {
            if (this.ddlSuspense.SelectedValueEx == null) { return; }
            if (this._fbs.CurrentItem.ClassStatus == ClassStatus.Updated) { return; }
            int suspenseId = Convert.ToInt32(this.ddlSuspense.SelectedValueEx);
            this.BindMaterial(suspenseId);

            SuspenseOrder suspenseOrder = this._suspenseOrderProcessor.FetchSuspenseOrderById(suspenseId);
            this._fbs.CurrentItem.QualityOrderDetails.Clear();
            suspenseOrder.SuspenseOrderDetails.ToList().ForEach(x => {
                this._fbs.CurrentItem.QualityOrderDetails.Add(new QualityOrderDetail() {
                    MaterialId = x.MaterialId,
                    SuspenseQuantity = x.SuspenseQuantity,
                    QualifiedQuantity = x.SuspenseQuantity
                });
            });
            this.dgvMaterialEdit.DataSourceEx = this._fbs.CurrentItem.QualityOrderDetails.ToList();
        }

        private void dgvMaterialEdit_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
            if (this.dgvMaterialEdit.Columns[e.ColumnIndex].Name == "QualifiedQuantity") {
                decimal sqValue = Convert.ToDecimal(this.dgvMaterialEdit["SuspenseQuantity", e.RowIndex].Value);
                decimal qqvalue = Convert.ToDecimal(this.dgvMaterialEdit[e.ColumnIndex, e.RowIndex].Value);
                this.dgvMaterialEdit.Rows[e.RowIndex].Cells["ErrMessage"].Value = qqvalue > sqValue ? "合格数量不能大于暂收数量" : string.Empty;
            }
        }
    }
}
